<script lang="ts">
	import type { RoadmapInfo } from '$lib/api/proto/roadmap_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { EllipsisVertical, Search } from 'lucide-svelte';
	import EditRoadmapModal from './EditRoadmapModal.svelte';
	import ConfirmModal from '$lib/components/modal/ConfirmModal.svelte';
	import { goto } from '$app/navigation';

	let showCreateModal = $state(false);
	let roadmapList: RoadmapInfo[] = $state([]);
	let updateRoadmapInfo: RoadmapInfo | null = $state(null);
	let removeRoadmapInfo: RoadmapInfo | null = $state(null);

	let tmpKeyword = $state('');
	let keyword = $state('');

	async function changeRoleTo(userRole: USER_ROLE) {
		if (userStore.userInfo == null || userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.userApiClient.updateBasic({
				sessionId: userStore.userSession,
				basicInfo: {
					...userStore.userInfo.basicInfo!,
					userRole: userRole
				}
			}).response
		);
		if (userStore.userInfo.basicInfo != undefined) {
			userStore.userInfo.basicInfo.userRole = userRole;
			userStore.userInfo = {
				...userStore.userInfo
			};
		}
		await loadRoadmapList();
	}

	async function loadRoadmapList() {
		if (userStore.userInfo == null || userStore.userSession == null) {
			return;
		}
		if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH) {
			const res = await callApi(
				appStore.roadmapApiClient.listMyOwn({
					sessionId: userStore.userSession
				}).response
			);
			roadmapList = res.roadmapList;
		} else if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT) {
			const res = await callApi(
				appStore.roadmapApiClient.listMy({
					sessionId: userStore.userSession
				}).response
			);
			roadmapList = res.roadmapList;
		}
	}

	async function onUpdateRoadmap(roadmapId: string) {
		if (userStore.userInfo == null || userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapApiClient.get({
				sessionId: userStore.userSession,
				roadmapId: roadmapId
			}).response
		);
		const tmpList = roadmapList.slice();
		const index = tmpList.findIndex((item) => item.roadmapId == roadmapId);
		if (index != -1 && res.roadmap != undefined) {
			tmpList[index] = res.roadmap;
			roadmapList = tmpList;
		}
	}

	async function removeRoadmap() {
		if (removeRoadmapInfo == null || userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapApiClient.remove({
				sessionId: userStore.userSession,
				roadmapId: removeRoadmapInfo.roadmapId
			}).response
		);
		await loadRoadmapList();
		removeRoadmapInfo = null;
		appStore.addToastMessage({
			level: 'success',
			content: '删除成长路线图成功',
			keepTime: 2000
		});
	}

	async function setEnableJoinApply(roadmap: RoadmapInfo, enable: boolean) {
		if (userStore.userSession == null || roadmap.basicInfo == undefined) {
			return;
		}
		await callApi(
			appStore.roadmapApiClient.update({
				sessionId: userStore.userSession,
				roadmapId: roadmap.roadmapId,
				basicInfo: {
					...roadmap.basicInfo,
					enableJoinApply: enable
				}
			}).response
		);
		await onUpdateRoadmap(roadmap.roadmapId);
	}

	$effect(() => {
		loadRoadmapList();
	});

	$effect(() => {
		if (tmpKeyword == '') {
			keyword = '';
		}
	});
</script>

<div class="pl-[100px] pr-[100px] pt-[10px]">
	<div class="flex justify-between border-b-2 border-base-200">
		<h3 class="text-3xl">我的路线图</h3>
		<div class="tabs tabs-box mb-1">
			<button
				class="tab {userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH
					? 'tab-active'
					: ''}"
				onclick={() => changeRoleTo(USER_ROLE.USER_ROLE_COACH)}
			>
				我是教练
			</button>
			<button
				role="tab"
				class="tab {userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT
					? 'tab-active'
					: ''}"
				onclick={() => changeRoleTo(USER_ROLE.USER_ROLE_STUDENT)}
			>
				我是学生
			</button>
		</div>
		<div class="flex items-center gap-4">
			<label class="input w-[180px]">
				<input
					type="search"
					class="input"
					placeholder="过滤标题"
					bind:value={tmpKeyword}
					onkeypress={(e) => {
						if (e.key === 'Enter') {
							keyword = tmpKeyword;
						} else if (e.key == 'Esc') {
							tmpKeyword = '';
						}
					}}
				/>
				<button type="button" class="btn btn-ghost p-1" onclick={() => (keyword = tmpKeyword)}
					><Search /></button
				>
			</label>
			{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
				<button class="btn btn-primary" onclick={() => (showCreateModal = true)}>创建</button>
			{/if}
		</div>
	</div>
	<div class="flex flex-wrap gap-2 p-2">
		{#each roadmapList.filter((item) => item.basicInfo?.name.includes(keyword)) as roadmap}
			<div class="card bg-base-300 w-[300px] h-[220px] shadow-sm">
				<div class="card-body">
					<div class="flex w-[260px] justify-between items-center">
						<h2
							class="card-title text-secondary max-w-[200px] overflow-hidden truncate"
							title={roadmap.basicInfo?.name}
						>
							{roadmap.basicInfo?.name}
						</h2>

						{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
							<div class="flex gap-2 items-center">
								<span>公开访问</span>
								<input
									type="checkbox"
									checked={roadmap.basicInfo?.enableJoinApply ?? false}
									class="toggle toggle-secondary toggle-sm"
									onchange={(e) => setEnableJoinApply(roadmap, e.currentTarget.checked)}
								/>
								<div class="dropdown">
									<div tabindex="0" role="button" class="btn btn-ghost p-1">
										<EllipsisVertical size={16} />
									</div>
									<ul
										class="menu dropdown-content bg-base-100 rounded-box z-1 w-[80px] p-2 shadow-sm gap-2"
									>
										<li>
											<button
												type="button"
												class="btn btn-ghost"
												onclick={() => (updateRoadmapInfo = roadmap)}>修改</button
											>
										</li>
										<li class="text-error">
											<button
												type="button"
												class="btn btn-ghost"
												onclick={() => (removeRoadmapInfo = roadmap)}>删除</button
											>
										</li>
									</ul>
								</div>
							</div>
						{/if}
					</div>

					<SimpleEditor data={roadmap.basicInfo?.desc} sizeClass="h-[80px]" readOnly />
					<div class="card-actions justify-end">
						<button
							class="btn btn-secondary"
							onclick={() => {
								goto(`/app/roadmap/map?roadmapId=${roadmap.roadmapId}`);
							}}>打开</button
						>
					</div>
				</div>
			</div>
		{/each}
	</div>
</div>

<div class="absolute -left-[10000px]">
	{#if showCreateModal}
		<EditRoadmapModal
			onCancel={() => (showCreateModal = false)}
			onOk={() => {
				showCreateModal = false;
				loadRoadmapList();
			}}
		/>
	{/if}
	{#if updateRoadmapInfo != null}
		<EditRoadmapModal
			roadmapInfo={updateRoadmapInfo}
			onCancel={() => (updateRoadmapInfo = null)}
			onOk={() => {
				onUpdateRoadmap(updateRoadmapInfo?.roadmapId ?? '');
				updateRoadmapInfo = null;
			}}
		/>
	{/if}
	{#if removeRoadmapInfo != null}
		<ConfirmModal
			title="删除路线图"
			content={`是否删除路线图${removeRoadmapInfo.basicInfo?.name}?`}
			type="error"
			okName="删除"
			onCancel={() => (removeRoadmapInfo = null)}
			onOk={() => removeRoadmap()}
		/>
	{/if}
</div>
